package com.jndv.phoneconfig.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.jndv.phoneconfig.MainActivity;
import com.jndv.phoneconfig.PublicConstant;
import com.jndv.phoneconfig.command.BatteryCommand;
import com.jndv.phoneconfig.websocket.JWebSocketClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

public abstract class BaseFragment extends Fragment {

    View view;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view=inflater.inflate(getLayoutId(),container,false);
        return view;
    }

    public abstract int getLayoutId();

    protected abstract void initView(View view);

    public JWebSocketClient getSocketClient(){
        MainActivity mainActivity= (MainActivity) getActivity();
        return mainActivity.getSocketClient();
    }

    public boolean isSocketConnect(){
        if(getSocketClient()==null || !getSocketClient().isOpen()){
            Toast.makeText(getActivity(),"请连接websocket",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    public void sendMessage(String type,String command){
        if(getSocketClient()==null || !getSocketClient().isOpen()){
            return;
        }

        Map<String,String> map=new HashMap<>();
        map.put(type,command);
        Gson gson=new Gson();
        getSocketClient().send(gson.toJson(map));
    }

    @Override
    public void onResume() {
        super.onResume();
        initView(view);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 该方法用不到,仅仅为了有个订阅事件不使程序崩溃
     * @param b
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(boolean b) {
    }

}
